package at.jaki.ubb.crawling.demo.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import at.jaki.ubb.crawling.api.CrawlingEngine;
import at.jaki.ubb.crawling.model.EngineStatus;
import at.jaki.ubb.crawling.model.Target;
import at.jaki.ubb.crawling.stlib.dataFinder.SimpleHttpClient;

public class Listener implements ActionListener, WindowListener {

	private CrawlingEngine ce;

	public Listener(CrawlingEngine ce) {
		this.ce = ce;
	}

	public void actionPerformed(ActionEvent e) {
		if (UiManager.ACTION_GO.equals(e.getActionCommand())) {
			String value = UiManager.getInstance().getSearch();
			String type = SimpleHttpClient.INPUT_TYPE;
			Target<String> t = new Target<String>(1D, value, type, value);
			ce.addTarget(t);
		}
		if (UiManager.ACTION_STATUS.equals(e.getActionCommand())) {
			EngineStatus status = ce.getStatus();
			UiManager.getInstance().showStatus(status);
		}
		if (UiManager.ACTION_RESET.equals(e.getActionCommand())) {
			UiManager.getInstance().clear();
			ce.stop();
			while (!ce.isStopped()) {
				try {
					Thread.sleep(1000);
				} catch (Exception e2) {
					// won't happen
				}
			}
			ce.startWithLastConfig();
		}

	}

	public void windowClosing(WindowEvent e) {
		ce.stop();
		System.exit(0);
	}

	public void windowOpened(WindowEvent e) {
	}

	public void windowClosed(WindowEvent e) {
	}

	public void windowIconified(WindowEvent e) {
	}

	public void windowDeiconified(WindowEvent e) {
	}

	public void windowActivated(WindowEvent e) {
	}

	public void windowDeactivated(WindowEvent e) {
	}

}
